/**
 *   Copyright 2014 Royce Remulla
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package cjcast.y2015.problem;


/**
 * @author royce.com@gmail.com
 */
public class SevenSegmentBean {


    /** */
    private final transient byte[] lEDSeq;

    /** */
    private final transient byte goodLED;


    /** */
    private final transient LEDState[] lEDState;


    /** */
    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    SevenSegmentBean(final String... pDigitFlagArr) {

        assert pDigitFlagArr != null;
        assert pDigitFlagArr.length > 0;

        this.lEDState = new LEDState[pDigitFlagArr.length];
        this.lEDSeq = new byte[pDigitFlagArr.length];
        for (int i = 0; i < pDigitFlagArr.length; i++) {
            lEDState[i] = new LEDState(pDigitFlagArr[i]);
            this.lEDSeq[i] = Byte.parseByte(pDigitFlagArr[i], 2);
        }

        goodLED = extractGoodLeds(lEDSeq);
    }

    /**
     * Extract working LEDs.
     * 
     * @param lEDSeq array of actual digit flags.
     */
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    final byte extractGoodLeds(final byte[] actualLEDSeq)
    {
        byte lGoodLED = 0;
        for (final byte nextLED : actualLEDSeq) {
            lGoodLED |= nextLED;
        }

        return lGoodLED;
    }


    public byte getGoodLED()
    {
        return goodLED;
    }

    public LEDState[] getLedState()
    {
        return lEDState.clone();
    }

    public byte[] getLEDSequence()
    {
        return lEDSeq.clone();
    }

    /** {@inheritDoc} */
    @Override
    public String toString()
    {
        final StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("Source: ");
        for (int i = 0; i < lEDSeq.length; i++) {
            strBuilder
                .append(
                    String
                        .format(
                            "%7s",
                            Integer.toBinaryString(lEDSeq[i]
                                    & LEDState.LED_ALL_ON))
                        .replace(' ', '0')).append(' ');
        }
        strBuilder.append(". Good: ").append(
            String.format(
                "%7s",
                Integer.toBinaryString(goodLED & LEDState.LED_ALL_ON)).replace(
                ' ',
                '0'));
        return strBuilder.toString();
    }
}
